package com.controller;

import org.h2.util.New;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dao.FriendRepository;
import com.dao.UserRepository;
import com.entity.Friend;
import com.entity.OnlineUser;
import com.entity.User;
import com.util.BaseUtil;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录等业务的控制类
 */
@Controller
public class WebController {

	/**
	 * 存放在线用户的信息,不包括用户的socket,key为uuid
	 */
	public static ConcurrentHashMap<String, OnlineUser> onlineUserMap = new ConcurrentHashMap<>();
	@Autowired
	private FriendRepository friendRepository;
	@Autowired
	private UserRepository userRepository;

	/**
	 * 页面的跳转
	 * 
	 * @param temName
	 * @return
	 */
	@RequestMapping("/go{temName}")
	public String toTemName(@PathVariable("temName") String temName) {
		return temName;// index页面也是登录页面
	}

	@RequestMapping("/")
	public String toIndex(Map<String, Object> model) {
		return "NewFile";// index页面也是登录页面
	}

	@RequestMapping("/index")
	public String toIndex2(Map<String, Object> model) {
		return "NewFile";// index页面也是登录页面
	}

	@RequestMapping("/new")
	public String test() {
		return "NewFile";
	}

	/**
	 * 登录提交的校验页面
	 * 
	 * @param customer
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> login(String uName, String upwdMd5, String cacheMD5) {
		try {
			Map<String, Object> model = new HashMap<>();
			// 根据用户名查出用户
			User user2 = userRepository.findByName(uName);
			if (user2 == null) {
				model.put("errorCode", 300);
				model.put("msg", "用户名或密码错误!");
				return model;
			}
			String upwdMd52 = BaseUtil.getHex_MD5(user2.getName() + "-" + user2.getPassword());
			if (upwdMd52.equals(upwdMd5)) {// 校验通过
				// 正确的话生成token(uuid)
				String uuid = UUID.randomUUID().toString();
				// 获得他的所有好友
				Set<Friend> friends = friendRepository.findByUserId(user2.getUserId());
				JSONObject friendsJSON = new JSONObject(friends);
				// 生成他的在线保存对象,并存放与onlinUsers中
				onlineUserMap.put(uuid, new OnlineUser(uuid, user2, friends));
				// 用户的json
				JSONObject userJSON = new JSONObject();
				userJSON.put("name", uName);
				userJSON.put("uPwdMd5", upwdMd5);

				// 获得用用户缓存信息的校验,缓存信息如果已过时则重新传给用户
				String sCacheMD5 = BaseUtil.getHex_MD5(friendsJSON.toString() + "-" + new JSONObject(user2).toString());
				if (!sCacheMD5.equals(cacheMD5)) {// 缓存存在
					model.put("friends", friends);// 好友
					user2.setPassword(upwdMd52);//用户的密码替换成MD5吗再传送到页面
					model.put("user", user2);// 自己
				}
				model.put("cacheMD5", sCacheMD5);// md5
				model.put("errorCode", 200);
				model.put("token", uuid);// 登录令牌
				return model;
			} else {
				model.put("errorCode", 300);
				model.put("msg", "用户名或密码错误!");
				return model;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			Map<String, Object> model = new HashMap<>();
			model.put("errorCode", 500);
			model.put("msg", e.getMessage());
			return model;
		}
	}
}